<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="slot">
            <el-row
              :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']"
              v-for="(item1,i1) in slot.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染出二级权限 -->
                <el-row
                  :class="['vcenter',i2 === 0 ?'':'bdtop']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(slot.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
              <!-- 此行数据 -->
              <!-- <pre> {{slot.row}}</pre> -->
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="slot">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditRole(slot.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(slot.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(slot.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色时的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addRoleVisible" width="50%" @close="addRoleClosed">
      <!-- 内容主体区域 -->
      <el-form ref="addFormRef" :model="addForm" label-width="70px" :rules="addFormRules">
        <el-form-item prop="roleName" label="角色名">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item prop="roleDesc" label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的对话框 -->
    <el-dialog title="修改角色" :visible.sync="editRoleVisible" width="50%" @close="editRoleClosed">
      <el-form ref="editFormRef" :model="editForm" label-width="70px">
        <el-form-item prop="roleName" label="角色名">
          <el-input v-model="editForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="clearDefKeys">
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表
      rolesList: [],
      // 控制添加角色对话框的显示与隐藏
      addRoleVisible: false,
      // 添加角色的表单数据
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间' },
        ],
      },
      // 修改角色的表单数据
      editForm: {
        id: '',
        roleName: '',
        roleDesc: '',
      },
      //控制修改用户对话框的显示与隐藏
      editRoleVisible: false,
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 分配权限的角色id
      roleId: '',
    };
  },
  created() {
    // 获取所有的角色
    this.getRolesList();
  },
  methods: {
    // 请求获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！');
      }
      this.rolesList = res.data;
      // console.log(this.rolesList);
    },
    // 监听添加角色信息对话框的关闭事件
    addRoleClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 监听修改角色信息对话框的关闭事件
    editRoleClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 发出添加角色的网络请求
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        // 发起真正的添加角色网络请求
        const { data: res } = await this.$http.post('roles', this.addForm);
        // console.log(res);
        // console.log(res.meta.status);
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败');
        }
        this.$message.success('添加角色成功');
        this.addRoleVisible = false;
        // 修改后更新列表
        this.getRolesList();
      });
    },
    // 展示编辑角色的对话框
    async showEditRole(id) {
      //   console.log(id);
      const { data: res } = await this.$http.get('roles/' + id);
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败');
      }
      this.editForm = res.data;
      this.editRoleVisible = true;
      // console.log(id);
    },
    // 修改角色信息并提交
    editRoleInfo() {
      // 预验证
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) {
          return;
        }
        // 预验证通过则发起数据请求
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );

        if (res.meta.status !== 200) {
          //   console.log(this.editForm);
          //   console.log(res);
          return this.$message.error('修改角色信息失败');
        }
        // 状态码200，提示成功->关闭对话框->更新用户列表
        this.$message.success('修改角色信息成功');
        this.editRoleVisible = false;
        this.getRolesList();
      });
    },
    // 根据id删除对应角色
    async removeRoleById(id) {
      // 弹框询问是否确认删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err);
      // 点击确认返回confirm字符串，取消返回cancel字符串
      // 此处为取消
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      // 确认后真正发起删除请求
      const { data: res } = await this.$http.delete('roles/' + id);
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！');
      }
      this.$message.success('删除角色成功！');
      this.getRolesList();
    },

    // 根据id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err);
      // 点击确认返回confirm字符串，取消返回cancel字符串
      // 此处为取消
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除权限');
      }
      // 确认后真正发起删除请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！');
      }
      this.$message.success('删除权限成功！');
      // this.getRolesList();
      role.children = res.data;
    },

    // 展示分配权限的对话框+获取数据
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败');
      }
      // 获取到的权限数据保存到data的rightsList中
      this.rightsList = res.data;
      // console.log(this.rightsList);
      // 递归获取已有三级权限
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },

    // 通过递归的形式，获取角色下所有的三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前节点不包含children属性既该节点是三级节点，则将id保存到数组中
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 清空deefKeys
    clearDefKeys() {
      this.defKeys = [];
    },
    // 点击为角色分配权限,赋值到数组中
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // console.log(keys);
      const idStr = keys.join(',');
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！');
      }
      this.$message.success('分配权限成功');
      // 请求成功后，重新获取角色权限列表，以及关闭对话框
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>